package org.amphiprion.descentv2assistant.ui.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.amphiprion.descentv2assistant.ApplicationConstants;
import org.amphiprion.descentv2assistant.R;
import org.amphiprion.descentv2assistant.adapter.MonsterListAdapter;
import org.amphiprion.descentv2assistant.adapter.TraitAdapter;
import org.amphiprion.descentv2assistant.dao.db.EncounterMonsterDao;
import org.amphiprion.descentv2assistant.dao.db.GameSessionDao;
import org.amphiprion.descentv2assistant.dao.xml.MonsterXmlDao;
import org.amphiprion.descentv2assistant.dao.xml.TraitXmlDao;
import org.amphiprion.descentv2assistant.entity.EncounterMonster;
import org.amphiprion.descentv2assistant.entity.GameSession;
import org.amphiprion.descentv2assistant.entity.Monster;
import org.amphiprion.descentv2assistant.entity.comparator.MonsterActComparator;
import org.amphiprion.descentv2assistant.filter.ExcludeFilter;
import org.amphiprion.descentv2assistant.ui.views.PinnedHeaderListView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class MonsterListFragment extends SherlockFragment implements AdapterView.OnItemClickListener {
	private boolean mActivityCreated;
	private MonsterListAdapter mAdapter;
	private List<Monster> mMonsters = new ArrayList();
	private PinnedHeaderListView mListView;
	private final Handler mHandler = new Handler();
	private View fragment;
	private final ExcludeFilter filter = new ExcludeFilter();

	public static MonsterListFragment sThis;

	private ActionMode.Callback mActionModeCallback;
	private ActionMode mActionMode;
	private Monster current;

	private View viewToUnselect;

	public static Fragment newInstance() {
		sThis = new MonsterListFragment();
		return sThis;
	}

	private void onLoadDone() {
		this.mListView.setAdapter(this.mAdapter);
		this.mListView.setOnScrollListener(this.mAdapter);
		this.mListView.setDividerHeight(0);
		this.mListView.setOnItemClickListener(this);

		this.mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> paramAnonymousAdapterView, View view, int index, long paramAnonymousLong) {
				// if (mActionMode != null) {
				// return false;
				// }
				// current = MonsterListFragment.this.mMonsters.get(index);
				// // Start the CAB using the ActionMode.Callback defined above
				// mActionMode = getSherlockActivity().startActionMode(mActionModeCallback);
				// view.setSelected(true);
				onItemClick(paramAnonymousAdapterView, view, index, paramAnonymousLong);
				return true;
			}
		});
		// this.mListView.post(new Runnable() {
		// @Override
		// public void run() {
		// Episode localEpisode = App.currentEpisode;
		// int i = 0;
		// if (localEpisode != null) {
		// for (int j = 0; j < EpisodeDiffusionListFragment.this.mEpisodes.size(); j++) {
		// if (EpisodeDiffusionListFragment.this.mEpisodes.get(j).getEpisodeId() == localEpisode.getEpisodeId()) {
		// i = j;
		// }
		// }
		// }
		// EpisodeDiffusionListFragment.this.mListView.setSelectionFromTop(i, App.dpiToPixels(getActivity(), 24));
		// }
		// });
	}

	public void initData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				mMonsters = MonsterXmlDao.getInstance().getMonsters(filter);
				Collections.sort(mMonsters, new MonsterActComparator());
				MonsterListFragment.this.mHandler.post(new Runnable() {
					@Override
					public void run() {
						if (MonsterListFragment.this.mAdapter == null) {
							mAdapter = new MonsterListAdapter(getActivity(), MonsterListFragment.this.mMonsters);
							MonsterListFragment.this.onLoadDone();
						} else {
							MonsterListFragment.this.mAdapter.setItems(MonsterListFragment.this.mMonsters);
							Log.d(ApplicationConstants.PACKAGE, "Reload Monstrers, nb=" + mMonsters.size());
						}
						// EpisodeDiffusionListFragment.this.mAdapter.setOnSeasonWatch(EpisodeDiffusionListFragment.sThis);
					}
				});
			}
		}).start();
	}

	@Override
	public void onActivityCreated(Bundle paramBundle) {
		super.onActivityCreated(paramBundle);
		this.mActivityCreated = true;
		this.mListView.setPinnedHeaderView(LayoutInflater.from(getActivity()).inflate(R.layout.list_monster_header, this.mListView, false));

		initData();
	}

	// @Override
	// public void onClick(View paramView) {
	// Log.d(ApplicationConstants.PACKAGE, "/**************** onClick");
	// Object localObject = paramView.getTag();
	// if ((localObject instanceof Monster)) {
	// Monster localEpisode = (Monster) localObject;
	// App.currentMonster = localEpisode;
	// // TODO voir detail d'un episode
	// // this.mApp.startEpisodeActivity(getActivity(), paramView);
	// }
	// }

	@Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);

		mActionModeCallback = new ActionMode.Callback() {

			@Override
			public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
				return false;
			}

			@Override
			public void onDestroyActionMode(ActionMode mode) {
				mActionMode = null;
				if (viewToUnselect != null) {
					viewToUnselect.setSelected(false);
					viewToUnselect = null;
				}
			}

			@Override
			public boolean onCreateActionMode(ActionMode mode, Menu menu) {
				MenuInflater inflater = mode.getMenuInflater();
				inflater.inflate(R.menu.context_all_monster, menu);
				return true;
			}

			@Override
			public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
				switch (item.getItemId()) {
				case R.id.menu_add_to_game:
					mode.finish(); // Action picked, so close the CAB

					final List<GameSession> games = GameSessionDao.getInstance(getActivity()).getAllVisible();
					Collections.sort(games);

					final CharSequence[] items = new CharSequence[games.size()];
					for (int i = 0; i < games.size(); i++) {
						items[i] = games.get(i).getName();
					}
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
					builder.setTitle(R.string.title_activity_choose_games);
					builder.setItems(items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int item) {
							EncounterMonster em = new EncounterMonster(current.getAct());
							em.setHealth(current.getCharacteristic().getHealth());
							em.setMonster(current);
							em.setGameId(games.get(item).getId());
							EncounterMonsterDao.getInstance(getActivity()).persist(em);

							Toast.makeText(getActivity(), current.getName() + " > " + games.get(item).getName(), Toast.LENGTH_LONG).show();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();

					return true;
				default:
					return false;
				}
			}
		};
	}

	@Override
	public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
		super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
		this.fragment = paramLayoutInflater.inflate(R.layout.fragment_monster_list, null);
		this.mListView = ((PinnedHeaderListView) this.fragment.findViewById(R.id.monsters));
		return this.fragment;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> paramAdapterView, View view, int index, long paramLong) {
		// Log.d(ApplicationConstants.PACKAGE, "/**************** onItemClick");
		// if (mActionMode != null) {
		// return;
		// }
		current = MonsterListFragment.this.mMonsters.get(index);
		// Start the CAB using the ActionMode.Callback defined above
		mActionMode = getSherlockActivity().startActionMode(mActionModeCallback);
		view.setSelected(true);
		viewToUnselect = view;
	}

	@Override
	public void onPause() {
		super.onPause();
		// sThis = null;
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	// @Override
	// public void onSeasonWatch(int serieId, String SeasonId, boolean watched) {
	// EpisodeDao.getInstance(getActivity()).watch(serieId, SeasonId, watched);
	// initData();
	// }

	public void scrollToTop() {
		this.mListView.smoothScrollToPosition(0);
	}

	public void doFilter() {

		final TraitAdapter adapter = new TraitAdapter(getActivity(), TraitXmlDao.getInstance().getTraits(), filter);

		final AlertDialog.Builder ad = new AlertDialog.Builder(getActivity());
		// define the alert dialog with the choices and the action to take
		// when one of the choices is selected
		ad.setSingleChoiceItems(adapter, -1, null);
		ad.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				initData();
			}
		});
		ad.show();

	}

}